<?php

namespace app\admin\controller;
use app\common\controller\Admin;
use think\Db;

class Adsmaterialbook extends Admin {
    /**
     * 小说对外开放接口
     *
     * @Author 小邓
     * @DateTime 2022-11-03
     * @return void
     */
	public function _initialize() {
		parent::_initialize();
    }

    public function index(){
        $keyword = input('get.keyword');
        $map     = [];
        if($keyword){
            $map['id|title'] = ["like","%$keyword%"];
        }
        $paltform = ['百度', '抖音', '知乎', '微博', '腾讯'];
        $list = db('ads_material_book')->where($map)->order("name desc,sort asc,id asc")->paginate( 200, false, [ 'type'=> 'page\Page' ,'query' => request()->param()] );
        foreach ($list as $k => $v) {
            $roi = json_decode($v['roi'], true);
            foreach ($paltform as $pk => $pv) {
                if (!isset($roi[$pv])) {
                    $roi[$pv] = ['roi' => 0,'roi_count' => 0];
                }
            }
            $v['roi'] = $roi;
            $list[$k] = $v;
        }
        $page = $list->render();
        $this->assign(compact('keyword', 'list', 'page'));
        $this->setMeta("账号管理");
        return view();
    }

    public function add() {
        set_time_limit(0);
        if(IS_POST){
            $post = input('post.');
            if( !$post['id'] ){
                $roi[$post['paltform']] = [
                    'roi' => $post['roi'],
                    'roi_count' => $post['roi_count']
                ];
                $post['roi'] = json_encode($roi);
                unset($post['roi_count']);
                $post['create_time'] = time();
                // $post['apikey'] = md5(uniqid());
                $book_id=db('ads_material_book')->insertGetId($post);
            
                if(!empty($post['file_path'])&&$book_id){
                    $post['book_id']=$book_id;
                    $post['create_time'] = time();
                    $post['name'] = $post['file_name']?'标本-'.$post['file_name']:'标本-'.basename($post['file_path']);
                    $post['uid']  = session('user_auth.uid');
                    $post['role_name']=$post['role_name']?implode(',',$post['role_name']):'';
                    Db::startTrans();
                    // 校验编码
                    $file = file_get_contents($post['file_path']);
                    $encoding = mb_detect_encoding($file, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
                    if ($encoding != 'UTF-8') {
                        $path =  './uploads'.DIRECTORY_SEPARATOR.'attachment'.DIRECTORY_SEPARATOR.date('Ymd').DIRECTORY_SEPARATOR;
                        $file_out = $path.md5(microtime(true)).".txt";
                        $file = iconv($encoding, "UTF-8", $file);
                        file_put_contents($file_out, $file);
                        $post['file_path'] = $file_out;
                    }
                    $txtId = db('upload_txt_log')->insertGetId($post);
                    $generatingDirectory = self::generatingDirectory($post['file_path'], $txtId);
                    $savedata = array_chunk($generatingDirectory,1000); // 防止文件过大 分割数组
                    foreach($savedata as $saveitem){
                        db('ads_book_directory')->insertAll($saveitem);
                    }
                    if(!empty($post['sample_name'])){
                        $sample_path=explode('.txt,',$post['sample_path']);
                        $sample_name=explode('.txt,',$post['sample_name']);
                        $post['role_name']='';
                        for($i=0;$i<count($sample_path);$i++){
                            if($i==count($sample_path)-1){
                                $post['name'] = '原文-'.$sample_name[$i];
                                $post['file_path']=$sample_path[$i];
                            }else{
                                $post['name'] = '原文-'.$sample_name[$i].'.txt';
                                $post['file_path']=$sample_path[$i].'.txt';
                            }
                            $file = file_get_contents($post['file_path']);
                            $encoding = mb_detect_encoding($file, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
                            if ($encoding != 'UTF-8') {
                                $path =  './uploads'.DIRECTORY_SEPARATOR.'attachment'.DIRECTORY_SEPARATOR.date('Ymd').DIRECTORY_SEPARATOR;
                                $file_out = $path.md5(microtime(true)).".txt";
                                $file = iconv($encoding, "UTF-8", $file);
                                file_put_contents($file_out, $file);
                                $post['file_path'] = $file_out;
                            }
                            $txtId = db('upload_txt_log')->insertGetId($post);
                         $generatingDirectory=[];
                            $generatingDirectory = self::generatingDirectory($post['file_path'], $txtId,1);
                            // 
                            $savedata = array_chunk($generatingDirectory,1000); // 防止文件过大 分割数组
                         
                            foreach($savedata as $saveitem){
                                db('ads_book_directory')->insertAll($saveitem);
                            }

                        }
                    }
                    Db::commit();
                }
            }else{
                $book = db('ads_material_book')->where('id', $post['id'])->value('roi');
                $book = json_decode($book, true);
                $book[$post['paltform']] = [
                    'roi' => $post['roi'],
                    'roi_count' => $post['roi_count']
                ];
                $post['roi'] = json_encode($book);
                $post['update_time'] = time();
                unset($post['roi_count']);
                db('ads_material_book')->update($post);
            }
            return $this->success("添加成功！");
        }
        return $this->error("失败！");
    }

    public function del() {
		$id = $this->getArrayParam('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
		$map['id'] = array('IN', $id);
		$result    = db('ads_material_book')->where($map)->delete();
		if (false !== $result) {
			return $this->success("删除成功！");
		} else {
			return $this->error("删除失败！");
		}
	}


    /**
     * Notes: 生成章节目录以及内容
     * @param $filepath
     * @param $bookId
     * @return array
     * @since: 2022/12/9 14:20
     * @author: Zhu
     */
    private function generatingDirectory($filepath, $txtId,$type=0)
    {
        $section=[];
        $i=0;
        $file = fopen($filepath,"r");
        $sort = 1;
        $num = 1;
        if ($file) {
            // 生成目录信息
            while(!feof($file)) {
                $line = fgets($file);
                $i += 1;
                if (strlen($line) < 3) {
                    continue;
                }
                $rt = preg_match_all("/第\s*[一二两三四五六七八九十○零百千万亿0-9１２３４５６７８９０]{1,50}\s*(章|话|节)[\s\S]*?(?:(?=\s*第\s*[一二两三四五六七八九十○零百千万亿0-9１２３４５６７８９０]{1,50}\s*(章|话|节))|$)/", $line, $arr);
                if (!$rt) {
                    continue;
                }

                $section[] = [
                    'txt_id' => $txtId,
                    'title'=>trim($arr[0][0]),
                    'line'=>$i,
                    'sort' => $sort
                ];
                $sort ++;
            }

            $myfile = file($filepath);
            
            foreach ($section as $k => $v) {
                $content = '';
                if (isset($section[$k+1])) {
                    for ($i = $v['line'] -1; $i < $section[$k+1]['line'] - 1; $i++) {
                        $content.= $myfile[$i] . '<br>';
                    }
                } else {
                    for ($i = $v['line'] -1; $i < count($myfile); $i++) {
                        $content.= $myfile[$i] . '<br>';
                    }
                }
                if (strlen($content) < 60) { // 防止章节重复
                    unset($section[$k]);
                    continue;
                }
                $section[$k]['num'] = $num;
                $section[$k]['content'] = $content;
                $section[$k]['create_time'] = time();
                $num ++;
            }
          
        }
    
        return $section;
    }
}